import java.net.*;
import java.io.*;
import java.util.Scanner;

public class NacosCompatibilityTest {
    private static final String SERVER_ADDR = "127.0.0.1:8848";
    
    public static void main(String[] args) {
        System.out.println("🧪 开始测试Rust Nacos服务器兼容性...");
        
        try {
            testHttpApi();
            System.out.println("✅ 所有兼容性测试通过！");
        } catch (Exception e) {
            System.err.println("❌ 测试失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    private static void testHttpApi() throws Exception {
        System.out.println("🔍 测试HTTP API...");
        
        // 测试1：健康检查
        testHealthCheck();
        
        // 测试2：注册服务实例
        testRegisterInstance();
        
        // 测试3：获取服务实例列表
        testGetInstances();
        
        // 测试4：发布配置
        testPublishConfig();
        
        // 测试5：获取配置
        testGetConfig();
        
        // 测试6：删除配置
        testDeleteConfig();
        
        // 测试7：注销服务实例
        testDeregisterInstance();
    }
    
    private static void testHealthCheck() throws Exception {
        String response = sendGetRequest("http://localhost:8848/health");
        System.out.println("✅ 健康检查通过: " + response);
    }
    
    private static void testRegisterInstance() throws Exception {
        String url = "http://localhost:8848/nacos/v1/ns/instance?namespace=public&serviceName=java-test-service&ip=127.0.0.1&port=8080&weight=1.0&healthy=true&enabled=true&ephemeral=true";
        String response = sendPostRequest(url, "");
        System.out.println("✅ 服务实例注册成功: " + response);
    }
    
    private static void testGetInstances() throws Exception {
        String response = sendGetRequest("http://localhost:8848/nacos/v1/ns/instance/list?namespace=public&serviceName=java-test-service");
        System.out.println("✅ 服务实例查询成功: " + response);
    }
    
    private static void testPublishConfig() throws Exception {
        String url = "http://localhost:8848/nacos/v1/cs/configs?namespace=public&group=DEFAULT_GROUP&dataId=java-test-config&content=test-content-from-java";
        String response = sendPostRequest(url, "");
        System.out.println("✅ 配置发布成功: " + response);
    }
    
    private static void testGetConfig() throws Exception {
        String response = sendGetRequest("http://localhost:8848/nacos/v1/cs/configs?namespace=public&group=DEFAULT_GROUP&dataId=java-test-config");
        System.out.println("✅ 配置获取成功: " + response);
    }
    
    private static void testDeleteConfig() throws Exception {
        String url = "http://localhost:8848/nacos/v1/cs/configs?namespace=public&group=DEFAULT_GROUP&dataId=java-test-config";
        String response = sendDeleteRequest(url, "");
        System.out.println("✅ 配置删除成功: " + response);
    }
    
    private static void testDeregisterInstance() throws Exception {
        String url = "http://localhost:8848/nacos/v1/ns/instance?namespace=public&serviceName=java-test-service&ip=127.0.0.1&port=8080";
        String response = sendDeleteRequest(url, "");
        System.out.println("✅ 服务实例注销成功: " + response);
    }
    
    private static String sendGetRequest(String urlString) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "application/json");
        
        return readResponse(conn);
    }
    
    private static String sendPostRequest(String urlString, String json) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        
        // 对于POST请求，参数应该在URL中，而不是请求体
        if (json != null && !json.isEmpty()) {
            conn.setDoOutput(true);
            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = json.getBytes("utf-8");
                os.write(input, 0, input.length);
            }
        }
        
        return readResponse(conn);
    }
    
    private static String sendDeleteRequest(String urlString, String json) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("DELETE");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        
        // 对于DELETE请求，参数应该在URL中，而不是请求体
        if (json != null && !json.isEmpty()) {
            conn.setDoOutput(true);
            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = json.getBytes("utf-8");
                os.write(input, 0, input.length);
            }
        }
        
        return readResponse(conn);
    }
    
    private static String readResponse(HttpURLConnection conn) throws Exception {
        int responseCode = conn.getResponseCode();
        InputStream is = (responseCode >= 200 && responseCode < 300) ? conn.getInputStream() : conn.getErrorStream();
        
        try (Scanner scanner = new Scanner(is, "UTF-8")) {
            scanner.useDelimiter("\\A");
            return scanner.hasNext() ? scanner.next() : "";
        }
    }
}